<?php

namespace app\cps\service;

use app\model\ResponsibilityPerson;
use app\model\PayRecord;
use app\model\Videos;
use app\model\OfficialAccounts;
use app\model\UserLoginRecord;
use app\model\User;
use app\model\Link;
use think\facade\Cache;
use app\model\DailyDeliveryData;

class StatisticsService
{
    private $model;
    private $payRecordModel;
    private $videosModel;
    private $officialAccountsModel;
    private $userLoginRecordModel;
    private $userModel;
    private $linkModel;
    private $dailyDeliveryDataModel;

    public function __construct(ResponsibilityPerson $model, PayRecord $payRecordModel, Videos $videosModel, OfficialAccounts $officialAccountsModel, UserLoginRecord $userLoginRecordModel, User $userModel, Link $linkModel, DailyDeliveryData $dailyDeliveryDataModel)
    {
        $this->model = $model;
        $this->payRecordModel = $payRecordModel;
        $this->videosModel = $videosModel;
        $this->officialAccountsModel = $officialAccountsModel;
        $this->userLoginRecordModel = $userLoginRecordModel;
        $this->userModel = $userModel;
        $this->linkModel = $linkModel;
        $this->dailyDeliveryDataModel = $dailyDeliveryDataModel;
    }

    // 修改最近使用的公众号
    public function updateUsedOfficialAccount($officialAccountId, $userInfo)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(3);
        $id = $userInfo['cps_user_id'];

        $bool = $this->model->edit(['id' => $id, 'used_official_account_id' => $officialAccountId, 'updated_at' => time()]);

        if (!$bool) {
            return false;
        }

        $userInfo['cps_used_official_account_id'] = $officialAccountId;

        $data = $this->model->getInfoByWhere(['id' => $id], 'official_account_id, used_official_account_id');
        $officialAccountIds = explode(',', $data['official_account_id']);
        // 
        $officialAccountsData = $this->officialAccountsModel->getDataByWhere(['id' => $officialAccountIds], 'id, name, is_default, app_id');

        foreach ($officialAccountsData as $key => $item) {
            if ($item['id'] == $data['used_official_account_id']) {
                $officialAccountsData[$key]['used_official_account_id'] = 1;
            } else {
                $officialAccountsData[$key]['used_official_account_id'] = 0;
            }
        }

        $userInfo['cps_official_accounts_data'] = $officialAccountsData;
        // redis剩余时间
        $residueTime = $redis->ttl($userInfo['token']);
        // 重新存储更新后的值
        $redis->set($userInfo['token'], json_encode($userInfo), $residueTime);

        return $userInfo;
    }

    // 获取订单统计数据
    public function getOrderStatisticsData($params, $userInfo)
    {
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->model->getInfoById($responsibilityPersonId, 'is_distributor, token');

        $cpsUserName = $userInfo['cps_user_name'];

        $data = [];
        // 今日充值
        $toDay = date('Ymd');
        $where = [
            ['consume_date', '=', $toDay], ['total_fee', '>', 0]
        ];
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->model->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->model->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($cpsUserName != config('enum.cps_user_name')) {
            // 非cps账号只获取当前的账户的数据
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
            $where[] = ['link_id', 'in', $linkIds];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }
        // 今日充值
        $toDayRechargeData = $this->payRecordModel->getInfo($where, 'activation_date, video_id, total_fee, type, status, uid');
        // 今日新用户
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            $data = $this->model->getInfoById($responsibilityPersonId, 'official_account_id');
            $officialAccountIds = explode(',', $data['official_account_id']);
            // $userData = $this->userModel->getBatchDataByWhere(['register_date' => $toDay, 'official_account_id' => $officialAccountIds], 'id');
        }
        // else if (!empty($distributorInfo['is_distributor']) || $cpsUserName != config('enum.cps_user_name')) {
        //     $userData = $this->userModel->getBatchDataByWhere(['register_date' => $toDay, 'official_account_id' => $usedOfficialAccountId, 'link_id' => $linkIds], 'id');
        // } else {
        //     $userData = $this->userModel->getBatchDataByWhere(['register_date' => $toDay, 'official_account_id' => $usedOfficialAccountId], 'id');
        // }
        // $uids = array_column($userData, 'id');

        $toDayRecharge = $toDayProfit = $toDayOrdinaryRecharge = $toDayMemberRecharge = $ordinaryPaid  = $ordinaryUnpaid = $memberPaid = $memberUnpaid = $newUserRecharge = 0;
        $toDayRechargeResult = $toDayVideoIds = [];

        foreach ($toDayRechargeData as $item) {

            if ($item['status'] == 1) {
                // $toDayRechargeResult[$item['video_id']][] = $item['total_fee'];
                $toDayRecharge = $toDayRecharge + $item['total_fee'];
                // $toDayVideoIds[] = $item['video_id'];
                if ($item['activation_date'] == $toDay) {
                    $newUserRecharge = $newUserRecharge + $item['total_fee'];
                }

                if ($item['type'] == 1) {
                    // 普通充值
                    $toDayOrdinaryRecharge = $toDayOrdinaryRecharge + $item['total_fee'];
                    $ordinaryPaid++;
                } else {
                    // 会员充值
                    $toDayMemberRecharge = $toDayMemberRecharge + $item['total_fee'];
                    $memberPaid++;
                }
            } else {

                if ($item['type'] == 1) {
                    // 普通充值
                    $ordinaryUnpaid += 1;
                } else {
                    // 会员充值
                    $memberUnpaid++;
                }
            }
        }

        // 今日收益
        // $videoData = $this->videosModel->getDataByIds($toDayVideoIds, 'id, scale');
        // $scaleData = array_column($videoData, 'scale', 'id');

        // foreach ($toDayRechargeResult as $key => $item) {
        //     if (!empty($scaleData[$key])) {
        //         $toDayProfit = $toDayProfit + array_sum($item) * $scaleData[$key] / 100;
        //     } else {
        //         $toDayProfit = $toDayProfit + array_sum($item);
        //     }
        // }

        $data['to_day_recharge']          = round($toDayRecharge, 2);
        // $data['to_day_profit']            = round($toDayProfit, 2);
        $data['to_day_new_user_recharge'] = round($newUserRecharge, 2);
        $data['to_day_ordinary_recharge'] = round($toDayOrdinaryRecharge, 2);
        $data['to_day_member_recharge']   = round($toDayMemberRecharge, 2);
        $data['to_day_ordinary_paid']     = $ordinaryPaid;
        $data['to_day_ordinary_unpaid']   = $ordinaryUnpaid;
        $data['to_day_member_paid']       = $memberPaid;
        $data['to_day_member_unpaid']     = $memberUnpaid;

        // pv/uv
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            $userLoginData = $this->userLoginRecordModel->getDataByWhere(['date' => $toDay, 'official_account_id' => $officialAccountIds]);
        } else if ($cpsUserName != config('enum.cps_user_name') || !empty($distributorInfo['is_distributor'])) {
            $userLoginData = $this->userLoginRecordModel->getDataByWhere(['date' => $toDay, 'official_account_id' => $usedOfficialAccountId, 'link_id' => $linkIds]);
        } else {
            $userLoginData = $this->userLoginRecordModel->getDataByWhere(['date' => $toDay, 'official_account_id' => $usedOfficialAccountId]);
        }

        $userLoginRecord = [];
        $pv = $uv = 0;
        foreach ($userLoginData as $item) {
            $pv++;
            $userLoginRecord[$item['uid']] = $item['id'];
        }
        $data['pv'] = $pv;
        $data['uv'] = count($userLoginRecord);

        // 如果当前时间在当天之内只需要返回今日数据
        $currentStartTime = strtotime(date('Y-m-d'). '00:00:00') + 60;
        $currentEndTime = strtotime(date('Y-m-d'). '23:59:59');
        if (empty($params['is_first'])) { // 第一次进入
            if (time() < $currentEndTime || $currentStartTime < time()) {
                return $data;
            }
        }

        // 昨日充值
        $yesterDay = date('Ymd', time() - 86400);
        $where = [
            ['activation_date', '=', $yesterDay], ['total_fee', '>', 0]
        ];
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($cpsUserName != config('enum.cps_user_name') || !empty($distributorInfo['is_distributor'])) {
            // 非cps账号只获取当前的账户的数据
            $where[] = ['link_id', 'in', $linkIds];
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }
        $yesterDayRechargeData = $this->payRecordModel->getInfo($where, 'video_id, total_fee, type, status');

        $yesterDayRecharge = $yesterDayProfit = $yesterDayOrdinaryRecharge = $yesterDayMemberRecharge = $yesterDayPaid  = $yesterDayUnpaid = $yesterDayMemberPaid = $yesterDayMemberUnpaid = 0;
        $yesterDayRechargeResult = $yesterDayVideoIds = [];

        foreach ($yesterDayRechargeData as $item) {
            if ($item['status'] == 1) {
                // $yesterDayRechargeResult[$item['video_id']][] = $item['total_fee'];
                $yesterDayRecharge = $yesterDayRecharge + $item['total_fee'];
                // $yesterDayVideoIds[] = $item['video_id'];

                if ($item['type'] == 1) {
                    // 普通充值
                    $yesterDayOrdinaryRecharge = $yesterDayOrdinaryRecharge + $item['total_fee'];
                    $yesterDayPaid++;
                } else {
                    // 会员充值
                    $yesterDayMemberRecharge = $yesterDayMemberRecharge + $item['total_fee'];
                    $yesterDayMemberPaid++;
                }
            } else {
                if ($item['type'] == 1) {
                    // 普通充值
                    $yesterDayUnpaid++;
                } else {
                    // 会员充值
                    $memberUnpaid++;
                    $yesterDayMemberUnpaid++;
                }
            }
            
        }

        // 昨日收益
        // $videoData = $this->videosModel->getDataByIds($yesterDayVideoIds, 'id, scale');
        // $scaleData = array_column($videoData, 'scale', 'id');

        // foreach ($yesterDayRechargeResult as $key => $item) {
        //     if (!empty($scaleData[$key])) {
        //         $yesterDayProfit = $yesterDayProfit + array_sum($item) * $scaleData[$key] / 100;
        //     } else {
        //         $yesterDayProfit = $yesterDayProfit + array_sum($item);
        //     }
        // }

        $data['yester_day_recharge']          = round($yesterDayRecharge, 2);
        // $data['yester_day_profit']            = round($yesterDayProfit, 2);
        $data['yester_day_ordinary_recharge'] = round($yesterDayOrdinaryRecharge, 2);
        $data['yester_day_member_recharge']   = round($yesterDayMemberRecharge, 2);
        $data['yester_day_ordinary_paid']     = $yesterDayPaid;
        $data['yester_day_ordinary_unpaid']   = $yesterDayUnpaid;
        $data['yester_day_member_paid']       = $yesterDayMemberPaid;
        $data['yester_day_member_unpaid']     = $yesterDayMemberUnpaid;

        // 本月充值
        $thisMonthStartDate = date('Ym'.'01');
        $thisMonthEndDate = date('Ymd');

        $where = [
            ['activation_date', '>=', $thisMonthStartDate],
            ['activation_date', '<', $thisMonthEndDate],
            ['total_fee', '>', 0]
        ];
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name') || !empty($distributorInfo['is_distributor'])) {
            // 非cps账号只获取当前的账户的数据
            $where[] = ['link_id', 'in', $linkIds];
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }

        $thisMonthData = $this->payRecordModel->getInfo($where, 'video_id, total_fee, type, status');

        $thisMonthRecharge = $thisMonthProfit = $thisMonthOrdinaryRecharge = $thisMonthMemberRecharge = $thisMonthPaid  = $thisMonthUnpaid = $thisMonthMemberPaid = $thisMonthMemberUnpaid = 0;
        $thisMonthRechargeResult = $thisMonthVideoIds = [];

        foreach ($thisMonthData as $item) {
            if ($item['status'] == 1) {
                // $thisMonthRechargeResult[$item['video_id']][] = $item['total_fee'];
                $thisMonthRecharge = $thisMonthRecharge + $item['total_fee'];
                // $thisMonthVideoIds[] = $item['video_id'];

                if ($item['type'] == 1) {
                    // 普通充值
                    $thisMonthOrdinaryRecharge = $thisMonthOrdinaryRecharge + $item['total_fee'];
                    $thisMonthPaid++;
                } else {
                    // 会员充值
                    $thisMonthMemberRecharge = $thisMonthMemberRecharge + $item['total_fee'];
                    $thisMonthMemberPaid++;
                }
            } else {
                if ($item['type'] == 1) {
                    // 普通充值
                    $thisMonthUnpaid++;
                } else {
                    // 会员充值
                    $thisMonthMemberUnpaid++;
                }
            }
        }

        // 本月收益
        // $videoData = $this->videosModel->getDataByIds($thisMonthVideoIds, 'id, scale');
        // $scaleData = array_column($videoData, 'scale', 'id');

        // foreach ($thisMonthRechargeResult as $key => $item) {
        //     if (!empty($scaleData[$key])) {
        //         $thisMonthProfit = $thisMonthProfit + array_sum($item) * $scaleData[$key] / 100;
        //     } else {
        //         $thisMonthProfit = $thisMonthProfit + array_sum($item);
        //     }
        // }

        $data['this_month_recharge']          = round($thisMonthRecharge, 2);
        // $data['this_month_profit']            = number_format($thisMonthProfit, 2);
        $data['this_month_ordinary_recharge'] = round($thisMonthOrdinaryRecharge, 2);
        $data['this_month_member_recharge']   = round($thisMonthMemberRecharge, 2);
        $data['this_month_ordinary_paid']     = $thisMonthPaid;
        $data['this_month_ordinary_unpaid']   = $thisMonthUnpaid;
        $data['this_month_member_paid']       = $thisMonthMemberPaid;
        $data['this_month_member_unpaid']     = $thisMonthMemberUnpaid;

        // 累计充值
        $where = [
            ['activation_date', '<', $thisMonthEndDate],
            ['total_fee', '>', 0]
        ];
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($cpsUserName != config('enum.cps_user_name') || !empty($distributorInfo['is_distributor'])) {
            // 非cps账号只获取当前的账户的数据
            $where[] = ['link_id', 'in', $linkIds];
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }
        $totalData = $this->payRecordModel->getInfo($where, 'video_id, total_fee, type, status');

        $totalRecharge = $totalProfit = $totalOrdinaryRecharge = $totalMemberRecharge = $totalPaid  = $totalUnpaid = $totalMemberPaid = $totalMemberUnpaid = 0;
        $totalRechargeResult = $totalVideoIds = [];

        foreach ($totalData as $item) {
            if ($item['status'] == 1) {
                // $totalRechargeResult[$item['video_id']][] = $item['total_fee'];
                $totalRecharge = $totalRecharge + $item['total_fee'];
                // $totalVideoIds[] = $item['video_id'];

                if ($item['type'] == 1) {
                    // 普通充值
                    $totalOrdinaryRecharge = $totalOrdinaryRecharge + $item['total_fee'];
                    $totalPaid++;
                } else {
                    // 会员充值
                    $totalMemberRecharge = $totalMemberRecharge + $item['total_fee'];
                    $totalMemberPaid++;
                }
            } else {
                if ($item['type'] == 1) {
                    // 普通充值
                    $totalUnpaid++;
                } else {
                    // 会员充值
                    $totalMemberUnpaid++;
                }
            }
        }

        // 累计收益
        // $videoData = $this->videosModel->getDataByIds($totalVideoIds, 'id, scale');
        // $scaleData = array_column($videoData, 'scale', 'id');

        // foreach ($totalRechargeResult as $key => $item) {
        //     if (!empty($scaleData[$key])) {
        //         $totalProfit = $totalProfit + array_sum($item) * $scaleData[$key] / 100;
        //     } else {
        //         $totalProfit = $totalProfit + array_sum($item);
        //     }
        // }

        $data['total_recharge']          = number_format($totalRecharge, 2);
        // $data['total_profit']            = number_format($totalProfit, 2);
        $data['total_ordinary_recharge'] = number_format($totalOrdinaryRecharge, 2);
        $data['total_member_recharge']   = number_format($totalMemberRecharge, 2);
        $data['total_ordinary_paid']     = $totalPaid;
        $data['total_ordinary_unpaid']   = $totalUnpaid;
        $data['total_member_paid']       = $totalMemberPaid;
        $data['total_member_unpaid']     = $totalMemberUnpaid;
        // $data['token']                   = $distributorInfo['token']; // 分销商token

        return $data;
    }

    // 近7日充值统计
    public function getRechargeStatisticsData($userInfo)
    {
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        $responsibilityPersonId = $userInfo['cps_user_id'];

        $distributorInfo['is_distributor'] = 0;
        if (!empty($userInfo['pid'])) {
            $distributorInfo = $this->model->getInfoById($userInfo['pid'], 'is_distributor');
        }

        $cpsUserName = $userInfo['cps_user_name'];

        $endDate = time();
        $startDate = time() - 7 * 86400;

        $date = [];
        for ($i = 6; $i >= 0; $i--) {
            $date[] = date('Ymd', $startDate + $i * 86400);
        }

        $userLoginData = $payRecordData = $result = [];
        $type = 1;

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->model->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where = [['date', 'in', $date]];
            $where[] = ['link_id', 'in', $linkIds];
            $data = $this->dailyDeliveryDataModel->getDataByWhere($where, 'date, total_recharge');

        } else if (!empty($userInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->model->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where = [['activation_date', 'in', $date], ['total_fee', '>', 0]];
            $where[] = ['link_id', 'in', $linkIds];
            $type = 2;
            $data = $this->payRecordModel->getInfo($where, 'activation_date, video_id, total_fee, type, status, uid');

        } else if ($cpsUserName != config('enum.cps_user_name') && $distributorInfo['is_distributor'] == 1) {
            // 分销商投手账号
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where = [['activation_date', 'in', $date], ['total_fee', '>', 0]];
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
            $where[] = ['link_id', 'in', $linkIds];
            $data = $this->payRecordModel->getInfo($where, 'activation_date, video_id, total_fee, type, status, uid');
            $type = 2;
        } else if ($cpsUserName != config('enum.cps_user_name')) {
            // 分公司投手账号或自投投手账号
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where = [['date', 'in', $date]];
            $where[] = ['link_id', 'in', $linkIds];
            $data = $this->dailyDeliveryDataModel->getDataByWhere($where, 'date, total_recharge');

        } else {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where = [['date', 'in', $date]];
            $where[] = ['link_id', 'in', $linkIds];
            $data = $this->dailyDeliveryDataModel->getDataByWhere($where, 'date, total_recharge');
        }

        if ($type == 2) {
            foreach ($data as $value) {
                $payRecordData[$value['activation_date']][] = $value;
            }
        } else {
            foreach ($data as $value) {
                $payRecordData[$value['date']][] = $value;
            }
        }

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            $officialAccountData = $this->model->getInfoById($responsibilityPersonId, 'official_account_id');
            $officialAccountIds = explode(',', $officialAccountData['official_account_id']);
            $userLogin = $userLoginRecord = $this->userLoginRecordModel->getDataByWhere(['date' => $date, 'official_account_id' => $officialAccountIds], 'uid, date');
        } else if ($cpsUserName != config('enum.cps_user_name') || !empty($distributorInfo['is_distributor'])) {
            $userLogin = $userLoginRecord = $this->userLoginRecordModel->getDataByWhere(['date' => $date, 'official_account_id' => $usedOfficialAccountId, 'link_id' => $linkIds], 'uid, date');
        } else {
            $userLogin = $userLoginRecord = $this->userLoginRecordModel->getDataByWhere(['date' => $date, 'official_account_id' => $usedOfficialAccountId], 'uid, date');
        }

        foreach ($userLoginRecord as $value) {
            $userLoginData[$value['date']][] = $value['uid'];
            $userLogin[$value['date']][$value['uid']] = $value['uid'];
        }

        foreach ($date as $dateTime) {
            $totalRecharge = $memberRecharge = 0; // 总充值/会员充值
            $ordinaryRecharge = 0; // 非会员充值金额
            $successPersonTime = $memberSuccessPersonTime = 0; // 非会员充值成功人次
            $paid = $unPaid = 0; // 普通已支付订单数/未支付订单数
            $memberPaid = $memberUnPaid = 0; // 会员充值已支付订单数/未支付订单数

            if (!empty($payRecordData[$dateTime])) {

                foreach ($payRecordData[$dateTime] as $key => $item) {
                    if ($type == 2) {
                        if ($item['status'] == 1) {
                            // 支付成功
                            $totalRecharge += $item['total_fee'];
                            if ($item['type'] == 1) {
                                // 普通充值
                                $ordinaryRecharge += $item['total_fee'];
                                // 成功人次
                                $successPersonTime = $successPersonTime + 1;
                                $paid++;
                            } else {
                                // 会员充值
                                $memberRecharge += $item['total_fee'];
                                $memberSuccessPersonTime++;
                                $memberPaid++;
                            }

                        } else {
                            // 待支付
                            if ($item['type'] == 1) {
                                $unPaid++;
                            } else {
                                $memberUnPaid++;
                            }
                        }
                    } else {
                        $totalRecharge += $item['total_recharge'];
                    }
                }

                if ($type == 2) {
                    $result[] = [
                        'date' => substr($dateTime, 0, 4) . '-' . substr($dateTime, 4, 2) . '-' . substr($dateTime, 6, 2),
                        'pv' => !empty($userLoginData[$dateTime]) ? count($userLoginData[$dateTime]) : 0,
                        'uv' => !empty($userLogin[$dateTime]) ? count($userLogin[$dateTime]) : 0,
                        'totalRecharge' => sprintf('%.2f', $totalRecharge),
                        'ordinaryRecharge' => sprintf('%.2f', $ordinaryRecharge),
                        'ordinary_successPersonTime' => $successPersonTime,
                        'ordinary_paid' => $paid,
                        'ordinary_unpaid' => $unPaid,
                        'memberRecharge' => round($memberRecharge, 2),
                        'memberSuccessPersonTime' => $memberSuccessPersonTime,
                        'memberPaid' => $memberPaid,
                        'memberUnPaid' => $memberUnPaid
                    ];
                } else {
                    $result[] = [
                        'date' => substr($dateTime, 0, 4) . '-' . substr($dateTime, 4, 2) . '-' . substr($dateTime, 6, 2),
                        'pv' => !empty($userLoginData[$dateTime]) ? count($userLoginData[$dateTime]) : 0,
                        'uv' => !empty($userLogin[$dateTime]) ? count($userLogin[$dateTime]) : 0,
                        'totalRecharge' => sprintf('%.2f', $totalRecharge),
                    ];
                }
            } else {
                if ($type == 2) {
                    $result[] = [
                        'date' => substr($dateTime, 0, 4) . '-' . substr($dateTime, 4, 2) . '-' . substr($dateTime, 6, 2),
                        'pv' => !empty($userLoginData[$dateTime]) ? count($userLoginData[$dateTime]) : 0,
                        'uv' => !empty($userLogin[$dateTime]) ? count($userLogin[$dateTime]) : 0,
                        'totalRecharge' => $totalRecharge,
                        'ordinaryRecharge' => $ordinaryRecharge,
                        'ordinary_successPersonTime' => $successPersonTime,
                        'ordinary_paid' => $paid,
                        'ordinary_unpaid' => $unPaid,
                        'memberRecharge' => round($memberRecharge, 2),
                        'memberSuccessPersonTime' => $memberSuccessPersonTime,
                        'memberPaid' => $memberPaid,
                        'memberUnPaid' => $memberUnPaid,
                    ];
                } else {
                    $result[] = [
                        'date' => substr($dateTime, 0, 4) . '-' . substr($dateTime, 4, 2) . '-' . substr($dateTime, 6, 2),
                        'pv' => !empty($userLoginData[$dateTime]) ? count($userLoginData[$dateTime]) : 0,
                        'uv' => !empty($userLogin[$dateTime]) ? count($userLogin[$dateTime]) : 0,
                        'totalRecharge' => sprintf('%.2f', $totalRecharge),
                    ];
                }
            }
        }

        return ['type' => $type, 'data' => $result];
    }

    // 短剧统计
    public function getVideoStatisticsData($userInfo)
    {
        $data = $this->videosModel->getDataByWhere([], 'id, name');

        $guideRecharge = $directRecharge = $guideRechargeNum = $directRechargeNum = 0;

        $videoIds = array_column($data, 'id');

        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->model->getInfoById($responsibilityPersonId, 'is_distributor');

        $cpsUserName = $userInfo['cps_user_name'];

        // 累计充值数据
        $totalRechargeQueryWhere = [
            ['video_id', 'in', $videoIds],
            ['status', '=', 1],
            ['consume_date', '<=', date('Ymd')],
            ['type', 'in', [1, 2]]
        ];

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->model->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;

            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $totalRechargeQueryWhere[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->model->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $totalRechargeQueryWhere[] = ['link_id', 'in', $linkIds];
        } else if ($cpsUserName != config('enum.cps_user_name')) {
            // 非cps账号只获取当前的账户的数据
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $totalRechargeQueryWhere[] = ['link_id', 'in', $linkIds];
        } else {
            $totalRechargeQueryWhere[] = ['official_account_id', '=', $usedOfficialAccountId];
        }

        $totalRechargeData = $this->payRecordModel->getInfo($totalRechargeQueryWhere, 'video_id, total_fee, consume_date, link_id');

        foreach ($totalRechargeData as $value) {

            if ($value['link_id']) {
                // 引导充值
                $guideRecharge = $guideRecharge + round($value['total_fee'], 2);
                $guideRechargeNum++;
            } else {
                // 直接充值
                $directRecharge = $directRecharge + round($value['total_fee'], 2);
                $directRechargeNum++;
            }
        }

        return [
            'guide_recharge' => round($guideRecharge, 2),
            'guide_recharge_num' => $guideRechargeNum,
            'direct_recharge' => round($directRecharge, 2),
            'direct_recharge_num' => $directRechargeNum
        ];
    }

    // 获取短剧统计列表
    public function getVideoStatisticsListData($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        $responsibilityPersonId = $userInfo['cps_user_id'];

        $distributorInfo = $this->model->getInfoById($responsibilityPersonId, 'is_distributor, pid, video_ids');

        $cpsUserName = $userInfo['cps_user_name'];

        if (!empty($distributorInfo['is_distributor'])) {
            $videoIds = explode(',', $distributorInfo['video_ids']);
            $where[] = ['id', 'in', $videoIds];
        } else if (!empty($distributorInfo['pid'])) {
            $distributor = $this->model->getInfoByWhere(['id' => $distributorInfo['pid']], 'is_distributor, video_ids');
            $videoIds = explode(',', $distributor['video_ids']);
            if (!empty($distributor['is_distributor'])) $where[] = ['id', 'in', $videoIds];
        }

        $data = $this->videosModel->getPagingDataByWhere($where, $page, $limit, 'id, name', 'sort desc');

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'id');

            $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];
            $toDay = $endDate = date('Ymd');

            // 今日充值数据
            $toDayWhere = [
                // 'video_id' => $videoIds,
                
                'consume_date' => $toDay,
                'status' => 1,
                'type' => [1, 2]
            ];

            if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
                // 分公司
                $responsibilityPersonData = $this->model->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
                $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
                $responsibilityPersonIds[] = $responsibilityPersonId;

                $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
                $linkIds = array_column($linkData, 'id');
                $toDayWhere['link_id'] = $linkIds;
            } else if (!empty($distributorInfo['is_distributor'])) {
                // 分销商能查看他下面的投手的数据
                $responsibilityPersonData = $this->model->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
                $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
                $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
                $linkIds = array_column($linkData, 'id');
                $toDayWhere['link_id'] = $linkIds;
            } else if ($cpsUserName != config('enum.cps_user_name')) {
                $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
                $linkIds = array_column($linkData, 'id');
                $toDayWhere['link_id'] = $linkIds;
            } else {
                $toDayWhere['official_account_id'] = $usedOfficialAccountId;
            }
            $toDayPayRecordData = $this->payRecordModel->getInfo($toDayWhere, 'video_id, total_fee');

            $toDayRecharge = [];
            foreach ($toDayPayRecordData as $value) {
                if(in_array($value['video_id'],$videoIds)){
                    $toDayRecharge[$value['video_id']][] = $value['total_fee'];
                }
            }

            // 累计充值数据
            $totalRechargeQueryWhere = [
                // ['video_id', 'in', $videoIds],
                ['status', '=', 1],
                ['consume_date', '<', $endDate],
                ['type', 'in', [1, 2]]
            ];
            if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
                $totalRechargeQueryWhere[] = ['link_id', 'in', $linkIds];
                $totalRechargeData = $this->payRecordModel->getInfo($totalRechargeQueryWhere, 'video_id, total_fee, consume_date, link_id');
            } else if ($cpsUserName != config('enum.cps_user_name') || !empty($distributorInfo['is_distributor'])) {
                $totalRechargeQueryWhere[] = ['link_id', 'in', $linkIds];
                $totalRechargeData = $this->payRecordModel->getInfo($totalRechargeQueryWhere, 'video_id, total_fee, consume_date, link_id');
            } else {
                $totalRechargeQueryWhere[] = ['official_account_id', '=', $usedOfficialAccountId];
                $totalRechargeData = $this->payRecordModel->getInfo($totalRechargeQueryWhere, 'video_id, total_fee, consume_date, link_id');
            }

            $totalRecharge = $yesterDayRecharge = [];
            $yesterDay = date('Ymd', time() - 86400);

            foreach ($totalRechargeData as $value) {
                if(in_array($value['video_id'],$videoIds)){
                    $totalRecharge[$value['video_id']][] = $value['total_fee'];
                    // 昨日充值
                    if ($value['consume_date'] == $yesterDay) {
                        $yesterDayRecharge[$value['video_id']][] = $value['total_fee'];
                    }
                }
            }

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['today_recharge'] = empty($toDayRecharge[$value['id']]) ? 0 : round(array_sum($toDayRecharge[$value['id']]), 2);
                $data['data'][$key]['yesterday_recharge'] = empty($yesterDayRecharge[$value['id']]) ? 0 : round(array_sum($yesterDayRecharge[$value['id']]), 2);
                $data['data'][$key]['total_recharge'] = empty($totalRecharge[$value['id']]) ? 0 : round(array_sum($totalRecharge[$value['id']]), 2);
            }
        }

        return $data;
    }
}